angular.module('Controller')
.controller 'WFMainCtrl', ($http,$scope, $rootScope,$localStorage,commonConstant,userData,menuManage, $location,$state)->
    $scope.$storage = $localStorage
    checkLogin = ->
        $http.get("@sunagy/Ui/ApiSunagy/loadLogin?token=#{userData.getToken()}")
        .success (resp)->
            if resp.code=='000_000'
                $state.go 'main'
            else
                $state.go 'login'
        .error (resp)->
            $state.go 'login'
    $grid = $('.grid');
    $root = $('#drag-layout-container');
    uuid = 0;
    grid = null;
    url = $location.search().url
    if (""+url).startWith("http")
        window.refreshContent(decodeURIComponent(url))
    $scope.newContainer =  if $state.params.uri=="new" then true else false
    if $scope.newContainer
        $root = $('#new-layout-container');
        $grid = $('#new-grid');

    $rootScope.navTabs={
        history:['welcome']
        active:'welcome',
        arrs:[{href:'welcome',icon:'fa-home',name:'',default:true}]
    }
    $scope.main = {
        brand: 'AdminerApp',
        name: 'Square Design'
    }
    $rootScope.chkSelected=(obj)->
        _.some(obj,(val,key)->val==true)
    $scope.admin = {
        layout: false,
        menu: false,
        fixedHeader: true,
        fixedSidebar: true,
        themeID: '24',
        navbarHeaderColor: 'bg-white',
        logo: 'bg-danger',
        asideColor: commonConstant.pageBg
    }
    $scope.color = {
        primary: '#248AAF',
        success: '#3CBC8D',
        info: '#29B7D3',
        purple: '#7266ba',
        warning: '#FAC552',
        danger: '#ED6D00'
    }
    $rootScope.goBack=(tabName)->
        if tabName!=undefined
            if _.some($rootScope.navTabs.history,(href)->href==tabName)
                $scope.clickTab(undefined ,tabName)
            else
                ''
        else
            len=$rootScope.navTabs.history.length
            preTab=$rootScope.navTabs.history[len-1] if len>0
            $scope.clickTab(undefined ,preTab)
    $scope.close = ->
        console.log 'close'
        _.defer ->
            $("#modalContent iframe").attr("src", '');
            $("#modalContent").attr("style", 'display:none;');
            $("#ng-app").attr("style", 'overflow:scroll;');
    $scope.clickTab=(event,href)->
        if event
            event.preventDefault()
        if $rootScope.navTabs.active==href
            return
        $rootScope.navTabs.active=href
        $rootScope.navTabs.history=_.filter $rootScope.navTabs.history,(history)->history!=href
        $rootScope.navTabs.history.push href
#        console.log('clickTab.navTabs:',$rootScope.navTabs)
    $rootScope.closeCurrentPage=()->
        $scope.closeTab(undefined,$rootScope.navTabs.active)
    $scope.closeTab=(event,href)->
        if event
            event.preventDefault()
        $rootScope.navTabs.history=_.filter $rootScope.navTabs.history,(history)->history!=href
        $rootScope.navTabs.arrs=_.filter $rootScope.navTabs.arrs,(tab)->tab.href!=href
        if $rootScope.navTabs.active==href and $rootScope.navTabs.history.length>=1
            $rootScope.navTabs.active=$rootScope.navTabs.history[$rootScope.navTabs.history.length-1]

    generateElements = (data) ->
        ret = [];
        urlModules = $localStorage.currentMenu?.urlModules
        if $scope.newContainer
            urlModules = $localStorage.newMenu?.urlModules
        if data
            urlModules = data
        $.each urlModules, (index, value) ->
            width = "#{value.width}".replace '%',''
            height = "#{value.height}".replace 'px',''
            contentDiv = document.createElement('iframe');
            contentDiv.setAttribute('class', 'myiframe');
            contentDiv.setAttribute('style', 'height:' + value.height+';background-color:'+value.contentBackground);
            url = value.url
            contentDiv.setAttribute('src', url);
            editDiv = document.createElement("div");
            editDiv.setAttribute('class', 'edit-container');
            formGroup1 = document.createElement("div");
            formGroup1.setAttribute('class', 'form-group');
            label1 = document.createElement("label");
            label1.innerHTML = '宽度'
            myInput_1 = document.createElement("input");
            myInput_1.setAttribute('class', 'input_width');
            myInput_1.setAttribute('type', 'text');
            myInput_1.setAttribute('value', width);
            formGroup1.appendChild(label1)
            formGroup1.appendChild(myInput_1)

            formGroup2 = document.createElement("div");
            formGroup2.setAttribute('class', 'form-group');
            label2 = document.createElement("label");
            label2.innerHTML = '高度'
            myInput_2 = document.createElement("input");
            myInput_2.setAttribute('class', 'input_height');
            myInput_2.setAttribute('type', 'text');
            myInput_2.setAttribute('value', height);
            formGroup2.appendChild(label2)
            formGroup2.appendChild(myInput_2)

            formGroup3 = document.createElement("div");
            formGroup3.setAttribute('class', 'form-group');
            label3 = document.createElement("label");
            label3.innerHTML = '标题'
            myInput_3 = document.createElement("input");
            myInput_3.setAttribute('type', 'text');
            myInput_3.setAttribute('value', value.title);
            formGroup3.appendChild(label3)
            formGroup3.appendChild(myInput_3)

            formGroup4 = document.createElement("div");
            formGroup4.setAttribute('class', 'form-group');
            label4 = document.createElement("label");
            label4.innerHTML = 'URL'
            myInput_4 = document.createElement("input");
            myInput_4.setAttribute('type', 'text');
            myInput_4.setAttribute('value', value.url);
            formGroup4.appendChild(label4)
            formGroup4.appendChild(myInput_4)

            myInput_5 = document.createElement("input");
            myInput_5.setAttribute('class', 'hidden');
            myInput_5.setAttribute('type', 'text');
            myInput_5.setAttribute('value', value.order);

            saveBtn = document.createElement("button");
            saveBtn.setAttribute('class', 'input_save btn btn-primary btn-w-md');
            saveBtn.innerText = '保存';

            editDiv.appendChild(formGroup1);#宽度
            editDiv.appendChild(formGroup2);#高度
            editDiv.appendChild(formGroup3);#标题
            editDiv.appendChild(formGroup4);#url
            editDiv.appendChild(myInput_5);#顺序
            editDiv.appendChild(saveBtn);#保存

            moreBtn = document.createElement("button");
            moreBtn.setAttribute('class', 'more btn btn-primary btn-w-md');
            span = document.createElement("span");
            span.innerText = '更多';
            i = document.createElement("i");
            i.setAttribute('class', 'fa fa-angle-right');
            i1 = document.createElement("i");
            i1.setAttribute('class', 'fa fa-angle-right');
            moreBtn.appendChild(span)
            moreBtn.appendChild(i)
            moreBtn.appendChild(i1)
            stuffDiv = document.createElement('div');
            stuffDiv.setAttribute('class', 'item-stuff');
            if value?.titleStyle
                $(stuffDiv).css(value.titleStyle)
            stuffDiv.innerText=value.title
            if eval(value?.needMore)
                $(moreBtn).on 'click',->
                    window.refreshContent(value?.moreUrl)
                stuffDiv.appendChild(moreBtn);
            innerDiv = document.createElement('div');
            innerDiv.setAttribute('class', 'item-content');
            innerDiv.appendChild(stuffDiv);
            innerDiv.appendChild(contentDiv);
            if $localStorage.setting
                innerDiv.appendChild(editDiv);
            height = parseInt((""+value.height).split("px")[0])
            if !eval(value?.hideborder)
                if value.containerStyle.border
                    height =height+parseInt(value.containerStyle.border.split("px")[0])*2
            else
                value.containerStyle.borderWidth ='0px'

            if eval((""+value.hideTitle).toLowerCase())
                $(stuffDiv).hide();
            else
                $(stuffDiv).show();
                height = height+44;
            outerDiv = document.createElement('div');
            outerDiv.setAttribute('class', 'item');
            if !value?.containerStyle
                value.containerStyle = {}
            _.extend value.containerStyle,
                width:99.9*(parseInt((""+value.width).split("%")[0])-0.5)/100+"%"
                height:height+'px'
                background:'#fff'
                marginLeft:'0.25%'
                marginRight:'0.25%'
            $(outerDiv).css(value.containerStyle)
            outerDiv.appendChild(innerDiv);
            ret.push(outerDiv);
            $(stuffDiv).on('click',value.func)
        ret
    init = (data)->
        console.log "init",$grid.get(0),$root.get(0)
        grid = new Muuri({
              container: $grid.get(0),
              items: generateElements(data),
              dragEnabled: $localStorage.setting,
              dragReleaseEasing: 'ease-in',
              dragContainer: $root.get(0)
        })
        top.grid = grid;
        refresh()
        layout()
    destroy=()->
        if grid
            grid.destroy();
            $grid.empty();
            grid = null;
            uuid = 0;

    show=()->
        if grid
            grid.show grid.get('inactive').slice(0, 5), (items)->
                console.log('CALLBACK: Hide ' + items.length + ' items')

    hide=()->
        if grid
            grid.hide grid.get('active').slice(0, 5), (items)->
                console.log('CALLBACK: Hide ' + items.length + ' items')

    add =()->
        if grid
            items = generateElements()
            _.each items,(item)->
                item.style.display = 'none'
            grid.show grid.add(items), (items)->
                console.log('CALLBACK: Added ' + items.length + ' items')

    remove=()->
        if grid
            grid.hide grid.get('active').slice(0, 4), (items)->
                grid.remove(items, true)
                console.log('CALLBACK: Removed ' + items.length + ' items');


    layout=()->
        if grid
            grid.layout ()->
                console.log('CALLBACK: Layout')

    refresh=()->
        if grid
            grid.refresh();

    synchronize=()->
        if grid
            grid.synchronize();
    $rootScope.$on 'refreshLayoutContainer',(obj,data)->
        console.log "refreshLayoutContainer",data
        if $localStorage.currentMenu?.urlModules
            _.delay ->
                destroy()
                init(data)
            ,500
    $rootScope.$on 'newLayoutContainer',(obj)->
        window.open "#/new"
    checkLogin()








